class WebsiteNavItem < ActiveRecord::Base
  attr_protected :created_at, :updated_at

  belongs_to :website_nav
  belongs_to :linked_to_item, :polymorphic => true
  
  protected_with_capabilities
  acts_as_nested_set

  include ErpTechSvcs::Utils::DefaultNestedSetMethods

  def path
    linked_to_item.nil? ? url : linked_to_item.path
  end
  
  def positioned_children
    children.sort_by{|child| [child.position]}
  end

  def website_nav
    website_nav_id.nil? ? self.parent.website_nav : WebsiteNav.find(website_nav_id)
  end

  def is_secured?
    self.protected_with_capability?('view')
  end
  
  def build_menu_item_hash
    {
        :title => self.title,
        :url => self.url,
        :roles => self.roles.collect(&:internal_identifier),
        :linked_to_item_type => self.linked_to_item_type,
        :linked_to_item_path => self.linked_to_item.nil? ? nil : self.linked_to_item.path,
        :position => self.position,
        :items => self.children.collect { |child| child.build_menu_item_hash }
    }
  end
  
end
